package container;

import domain.User;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * 注解上下文容器
 * @author jackcfan
 * @date 2021/9/12
 */
//@Configuration
public class AnnotationContext {

    @Test
    public void test(){
        // 创建注解容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        // 加载注解配置类 @Configuration
        applicationContext.register(this.getClass());

        // 启动上下文
        // AbstractApplicationContext.refresh
        // private final Object startupShutdownMonitor = new Object();
        // 启动时先加锁，确保线程安全
        applicationContext.refresh();

        User user = applicationContext.getBean(User.class);
        System.out.println(user);

        // 关闭时如果注册了 shutdownHook ，则会执行
        applicationContext.close();
    }

    /**
     * 通过 @Bean 注解定义一个 Bean
     * */
    @Bean
    public User user(){
        User user = new User();
        user.setId(123L);
        user.setName("spring");
        return user;
    }
}
